package veetouch.gallery;

import java.util.ArrayList;

import veetouch.syncpc.R;
import veetouch.syncpc.VtAndroidSyncActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class GalleryActivity extends Activity
{
	private int count;
	private Bitmap[] thumbnails;
	private int[] thumbnailsTempId;
	private Bitmap thumbnailsTemp;
	private boolean[] thumbnailsselection;
	private String[] arrPath;
	
	private ImageAdapter imageAdapter;
	
	private Button shareBtn;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery);
        
        // Set default button
        Button button_home = (Button) findViewById(R.id.Button_home);
        button_home.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View arg0) 
			{
				onBackPressed();
			}
		});
        
        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media.DATE_ADDED;
        Cursor imagecursor = managedQuery(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
				null, orderBy);
		int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
		this.count = imagecursor.getCount();
		this.thumbnails = new Bitmap[this.count];
		this.thumbnailsTempId = new int[this.count];
		this.arrPath = new String[this.count];
		this.thumbnailsselection = new boolean[this.count];
		
		Resources res = getResources();
		Drawable drawable = res.getDrawable(R.drawable.icon_contact);
		this.thumbnailsTemp = ((BitmapDrawable)drawable).getBitmap();
		
		for (int i = 0; i < this.count; i++) {
			imagecursor.moveToPosition(i);
			int id = imagecursor.getInt(image_column_index);
			int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
			this.thumbnailsTempId[i] = id;
			
			thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
					getApplicationContext().getContentResolver(),id,
					MediaStore.Images.Thumbnails.MICRO_KIND, null);
			
			/*
			thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
					getApplicationContext().getContentResolver(),id,
					MediaStore.Images.Thumbnails.MINI_KIND, null);
			*/
			arrPath[i]= imagecursor.getString(dataColumnIndex);
		}
		GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
		
		imageAdapter = new ImageAdapter();
		imagegrid.setAdapter(imageAdapter);
		
		/*
		this.imageAdapter = new LazyImageAdapter(
					this.getApplicationContext(),
					null,
					arrPath);
		imagegrid.setAdapter(imageAdapter);
		imagecursor.close();
		*/
		
		final Button clearBtn = (Button) findViewById(R.id.Button_clear);
		clearBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) 
			{
				onBackPressed();
				Intent intent = new Intent(getApplicationContext(),GalleryActivity.class);
				startActivity(intent);
				/*
				for(int i = 0;i<imageAdapter.holderSelectList.size();i++)
				{
					imageAdapter.holderSelectList.get(i).checkbox.setChecked(false);
					thumbnailsselection[i] = false;
				}
				shareBtn.setText("Share");
				*/
			}
		});
		
		
		shareBtn = (Button) findViewById(R.id.Button_share);
		shareBtn.setOnClickListener(new OnClickListener() 
		{
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				final int len = thumbnailsselection.length;
				int cnt = 0;
				ArrayList<String> selectImages = new ArrayList<String>();
				//String selectImages = "";
				for (int i =0; i<len; i++)
				{
					if (thumbnailsselection[i]){
						cnt++;
						selectImages.add( arrPath[i]);
						//selectImages = selectImages + arrPath[i] + "|";
					}
				}
				if (cnt == 0)
				{
					Toast.makeText(getApplicationContext(),"Please select at least one image",Toast.LENGTH_LONG).show();
				}
				else 
				{
					Toast.makeText(getApplicationContext(),
							"You've selected Total " + cnt + " image(s).",
							Toast.LENGTH_LONG).show();
					
					Intent intent = new Intent(getApplicationContext(),VtAndroidSyncActivity.class);
					intent.putExtra("SYNC_TYPE",VtAndroidSyncActivity.SYNC_TYPE_UPLOAD_PHOTO);
					String[] datas = new String[selectImages.size()];
					selectImages.toArray(datas);
					intent.putExtra("DATA",datas);
					startActivity(intent);
					
					//onDestroy();
					onBackPressed(); // Close this page
				}
			}
		});
    }
    
    private void setCountShareNumber()
	{
    	final int len = thumbnailsselection.length;
		int cnt = 0;
		for (int i =0; i<len; i++)
		{
			if (thumbnailsselection[i])
			{
				cnt++;
			}
		}
		if(cnt == 0)
		{
			this.shareBtn.setText("Share");
		}
		else
		{
			this.shareBtn.setText("Share ("+cnt+")");
		}
	}
    
    public class ImageAdapter extends BaseAdapter 
    {
		private LayoutInflater mInflater;

		public ImageAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return count;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) 
		{
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.galleryitem, null);
				holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
				holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
				
				convertView.setTag(holder);
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.checkbox.setId(position);
			holder.imageview.setId(position);
			
			holder.checkbox.setOnClickListener(new OnClickListener() 
			{	
				public void onClick(View v) 
				{
					CheckBox cb = (CheckBox) v;
					int id = cb.getId();
					if (thumbnailsselection[id])
					{
						cb.setChecked(false);
						thumbnailsselection[id] = false;
					} else {
						cb.setChecked(true);
						thumbnailsselection[id] = true;
					}
					setCountShareNumber();
				}
			});
			holder.imageview.setOnClickListener(new OnClickListener() 
			{
				public void onClick(View v) {
					// TODO Auto-generated method stub
					RelativeLayout layout = (RelativeLayout) v.getParent();
					CheckBox cb = (CheckBox)layout.getChildAt(1);
					int id = cb.getId();
					if (thumbnailsselection[id]){
						cb.setChecked(false);
						thumbnailsselection[id] = false;
					} else {
						cb.setChecked(true);
						thumbnailsselection[id] = true;
					}
					setCountShareNumber();
				}
			});
			holder.imageId = thumbnailsTempId[position];
			holder.imageview.setImageBitmap(thumbnails[position]);
			/*
			if(holder.realImage != null)
			{
				holder.imageview.setImageBitmap(holder.realImage);
			}
			else
			{
				holder.imageview.setImageBitmap(thumbnailsTemp);
			}
			*/
			
			holder.checkbox.setChecked(thumbnailsselection[position]);
			holder.id = position;
			
			return convertView;
		}
	}
	class ViewHolder implements Runnable
	{
		int id;
		int imageId = -1;
		ImageView imageview;
		CheckBox checkbox;
		Bitmap realImage = null;
		
		public ViewHolder()
		{
			//Thread loadImageT = new Thread(this);
			//loadImageT.start();
		}
		
		@Override
		public void run() 
		{ 
			boolean loadcomplete = false;
			while(loadcomplete == false)
			{
				try {Thread.sleep(80);} catch (InterruptedException e) {e.printStackTrace();}
				if(imageview != null && imageId != -1)
				{
					// TODO Auto-generated method stub
					final Bitmap thumbnails = MediaStore.Images.Thumbnails.getThumbnail(
							getApplicationContext().getContentResolver(),imageId,
							MediaStore.Images.Thumbnails.MINI_KIND, null);
					this.realImage = thumbnails;
					runOnUiThread(new Runnable() {
						public void run() {
							imageview.setImageBitmap(thumbnails);
						}
					});
					loadcomplete = true;
					break;
				}
			}
		}
	}
}
